package org.mics.jpa.helper;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mics.jpa.vo.TreeNodeVO;

/**树结构
 * @author mics
 * @date 2023-9-26
 * @version  1.0
 */
public class TreeUtils {
	
	public static <T extends TreeNodeVO> T convertOneTree(List<T> list) {
		//找到根节点
		T root = null;
		for(T t:list) {
			if(StringUtils.isBlank(t.getParentId())) {
				root = t;
				break;
			}
		}
		searchChildrens(root,list);
		return root;
	}
	
	public static <T extends TreeNodeVO>  List<T>  convertMulTree(List<T> list) {
		//找到根节点
		List<T> ts = new ArrayList<T>();
		for(T t:list) {
			if(StringUtils.isBlank(t.getParentId())) {
				searchChildrens(t,list);
				ts.add(t);
			}
		}
		return ts;
	}
	
	
	public static <T extends TreeNodeVO>  void  searchChildrens(TreeNodeVO root,List<T> list) {
		List<TreeNodeVO> nodes = new ArrayList<TreeNodeVO>();
		//查找子节点
		for(TreeNodeVO t : list) {
			if(root.getId().equals(t.getParentId())) {
				nodes.add(t);
				searchChildrens(t,list);
			}
		}
		root.setChildrens(nodes);
	}
}
